package quiz;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Random;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SubmitAnswerServlet
 */
@WebServlet("/Question")
public class SubmitAnswerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SubmitAnswerServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		DataBase db = (DataBase) request.getServletContext().getAttribute("db");
		if (request.getParameter("id") != null) {
			int id = Integer.parseInt(request.getParameter("id"));
			
			int questionNum = ((ArrayList<QuizResponse>)request.getSession().getAttribute("answers")).size() + 1;
			
			Question q = db.getQuestion(id);
			request.setAttribute("currentQuestion", q);
			request.setAttribute("questionNumber", questionNum);
			
			RequestDispatcher d = request.getRequestDispatcher("show-question.jsp");
			d.forward(request, response);
		}
		else {
			ArrayList<Question> questionsLeft = (ArrayList<Question>)request.getSession().getAttribute("questionsLeft");
			
			if (questionsLeft.size() == 0) {
				response.sendRedirect("Result");
				//TODO check redirect when servlet created
			}
			else {
				
				Question question = questionsLeft.remove(0);
					
				request.getSession().setAttribute("questionsLeft", questionsLeft);	
				response.sendRedirect("Question?id="+question.getID());
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		DataBase db = (DataBase) request.getServletContext().getAttribute("db");
		//int quizID = Integer.parseInt(request.getParameter("quizID"));
		
		boolean answeredCorrect = false;
		
		HttpSession session = request.getSession();
		
		//if (quizID != ((Quiz)session.getAttribute("quiz")).getID()) {
			//System.out.println("Quiz ID mismatch...not even sure if we want to monitor this");
		//}
		
		Enumeration<?> e = request.getParameterNames();
		
		ArrayList<String> errors = new ArrayList<String>();
		int qNum = 0;
		
		while (e.hasMoreElements()) {
			answeredCorrect = false;
			String eleName = (String)e.nextElement();
			if (eleName.indexOf("answer") == -1) continue;
			
			//continue knowing we're working with an answer
			String value = (String)request.getParameter(eleName);
			
			//get the question id, which is appened to answer field
			qNum = Integer.parseInt(eleName.substring(6));
			Question q = db.getQuestion(qNum);
						
			ArrayList<Answer> correctList = Utilities.getCorrectAnswers(q.getAnswers());
			
			for (Answer a: correctList) {
				if (a.getContent().equals(value)) {
					answeredCorrect = true;
					
					int runningScore = (Integer)session.getAttribute("runningScore");
					session.setAttribute("runningScore",runningScore + q.getWeight());			
					break;
				}
			}
			
			if (!answeredCorrect) errors.add("You answer \""+value+"\" is incorrect");
			
			QuizResponse r = new QuizResponse(q, value, answeredCorrect);
			ArrayList<QuizResponse> answers = (ArrayList<QuizResponse>)session.getAttribute("answers");
			answers.add(r);
			session.setAttribute("answers", answers);
			session.setAttribute("runningPossibleScore", ((Integer)session.getAttribute("runningPossibleScore")) + q.getWeight());

		}
		Quiz curQuiz = (Quiz)session.getAttribute("quiz");
		
		if (curQuiz.should_correctImmediately()) {						
			if (errors.size() == 0) {
				request.setAttribute("success", "You answered the question(s) correctly");
			}
			else {
				String error = "<ul>";
				for(String s: errors) {
					error += "<li>"+s+"</li>"; 
				}
				request.setAttribute("error", error+"</ul>");
			}
			
			if (curQuiz.is_singlePage()) {
				RequestDispatcher dispatch = request.getRequestDispatcher("show-quiz.jsp");
				dispatch.forward(request, response);
			}
			else {
				int questionNum = ((ArrayList<QuizResponse>)request.getSession().getAttribute("answers")).size();
				request.setAttribute("questionNumber", questionNum);

				request.setAttribute("currentQuestion", db.getQuestion(qNum));
				
				RequestDispatcher dispatch = request.getRequestDispatcher("show-question.jsp");
				dispatch.forward(request, response);
			}
		}
		else {
			response.sendRedirect("Question");
		}
		
		
	}

}
